package com.uzhie.spring;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by TangFei on 2018/7/18.
 */
public class HttpApplicationContextAware implements ApplicationContextAware {

    private Logger logger = Logger.getLogger(this.getClass());
    private Map<String, HttpClassMethod> classMethodMap;

    public Map<String, HttpClassMethod> getClassMethodMap() {
        logger.info("end spring request mapping ......");
        return classMethodMap;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        logger.info("start spring request mapping ......");
        classMethodMap = new HashMap<>();
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(Controller.class);
        for (Map.Entry<String, Object> entry : beansWithAnnotation.entrySet()) {
            logger.error(entry.getKey() + "\t" + entry.getValue());
        }
        for (String key : beansWithAnnotation.keySet()) {
            Object o = beansWithAnnotation.get(key);
            Method[] methods = o.getClass().getMethods();
            for (Method method : methods) {
                boolean annotationPresent = method.isAnnotationPresent(RequestMapping.class);
                if (annotationPresent) {
                    logger.info(String.format("spring requestMethod [%s] ======= controller中的方法 [%s]", method.getAnnotation(RequestMapping.class).value(), method.toString()));
                    //classMethodMap.put(method.getAnnotation(RequestMapping.class).value(), new HttpClassMethod(o, method));
                }
            }
        }
    }

}
